<?php

namespace App\Traits;

use Illuminate\Http\JsonResponse;
use App\Enums\ResponseEnum;

trait ResponseTrait
{
    protected function succeed(array $data = [], int $code = ResponseEnum::HTTP_OK, ?string $message = ''): JsonResponse
    {
        return $this->jsonData('succeed', $code, $message, $data);
    }

    protected function fail(int $code = ResponseEnum::HTTP_FAIL, ?string $message = '', array $data = []): JsonResponse
    {
        return $this->jsonData('fail', $code, $message, $data);
    }

    protected function error(int $code = ResponseEnum::HTTP_ERROR, ?string $message = ''): JsonResponse
    {
        return $this->jsonData('error', $code, $message);
    }

    protected function abnormal(int $code = ResponseEnum::HTTP_ERROR, ?string $message = ''): JsonResponse
    {
        empty($message) && $message = ResponseEnum::getDescription($code);
        return $this->responseJson(["status" => 'error', "code" => $code, "message" => $message, "data" => []], $code);
    }

    protected function jsonData(string $status, int $code, ?string $message, array $data = []): JsonResponse
    {
        empty($message) && $message = ResponseEnum::getDescription($code);
        return $this->responseJson(["status" => $status, "code" => $code, "message" => $message, "data" => $data])->setEncodingOptions(JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    }

    protected function responseJson(array $data = [], $status = 200, array $headers = []): JsonResponse
    {
        return response()->json($data, $status, $headers);
    }
}
